package com.csj.lc.service;

import cn.hutool.crypto.SecureUtil;
import com.csj.lc.base.BaseService;
import com.csj.lc.entity.dto.ReturnDTO;
import com.csj.lc.entity.Url;
import com.csj.lc.entity.User;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Service
@Transactional
public class LoginService extends BaseService {

    public ModelAndView login(HttpServletRequest request, User user) {

        User userTemp = userMapper.query( user.getUserName() );
        if(userTemp == null){
            ModelAndView mv = new ModelAndView("redirect:index");
            request.getSession().setAttribute("msg","用户名不存在，请确认后重试!");
            return mv;
        }

        if( !userTemp.getPassword() .equals( SecureUtil.md5( user.getPassword())) ){
            ModelAndView mv = new ModelAndView("redirect:index");
            request.getSession().setAttribute("msg","密码错误，请重新登录!");
            return mv;
        }
        else {
            ModelAndView mv = new ModelAndView();
            mv.setViewName("redirect:home");
            userTemp.setPassword("密码是不能被看到的哦！");
            request.getSession().setAttribute("loginUser",userTemp);
            return mv;
        }
    }

    public ReturnDTO<User> csLogin(HttpServletRequest request, User user) {

        User userTemp = userMapper.query( user.getUserName() );
        if(userTemp == null){
            return new ReturnDTO<User>( -1,"不存在的用户，请确认后重试");
        }

        if( !userTemp.getPassword().equals( SecureUtil.md5( user.getPassword() )) ){
            return new ReturnDTO<User>( -1,"密码错误，请重新登录");
        }
        else {
            userTemp.setPassword("密码是不能被看到的哦！");
            return new ReturnDTO<User>( 0,"登录成功",userTemp,null);
        }
    }


    public String logout(HttpServletRequest request) {

        request.getSession().removeAttribute("loginUser");
        return "login";
    }


    public String home(HttpServletRequest request , Model model) {

        List<Url> urlList = urlMapper.queryFull();
//        for (Url url : urlList) {
//            System.out.println(url);
//        }
        model.addAttribute( "urlList",urlList);
        return "index";
    }
}
